<?php
 namespace app\models;
 /**
  * @desc 采购退货操作model
  * @author liaojianwen
  * @date 2017-04-27
  */
 use Yii;
 use app\models\BaseModel;
 use app\enum\EnumOther;
 use app\dao\PurchaseReturnDAO;
 use app\dao\PurchaseDAO;
 use app\dao\PurchaseDetailDAO;
 use app\dao\PurchaseReturnDetailDAO;
 use app\dao\ProductDAO;
 use app\dao\TransactionDAO;
 use app\dao\StockPileDAO;
 use app\helpers\Utility;
 use app\enum\EnumOriginType;
 use app\dao\ProductUpdateLogDAO;
 use app\dao\PayablesDAO;
 
 class PurchaseReturnModel extends BaseModel 
 {
 	/**
 	 * @desc 覆盖父方法返回对象
 	 * @author liaojianwen
 	 * @date 2017-04-27
 	 * @return PurchaseReturnModel
 	 */
 	public static function model($className=__CLASS__)
 	{
 		return parent::model($className);
 	}
 	
 	/**
 	 * @desc 查询采购入库（导入采购人库单）
 	 * @param $cond 查询条件
 	 * @param $pageInfo 页面信息
 	 * @author liaojianwen
 	 * @date 2017-04-27
 	 */
 	public function selectPurchase($cond, $pageInfo)
 	{
 		if(empty($pageInfo)){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','param is empty');
 		}
 		$result = PurchaseDAO::getInstance()->selectPurchase($cond, $pageInfo);
 		if(empty($result)){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','no data found');
 		}
 		return $this->handleApiFormat ( EnumOther::ACK_SUCCESS, $result );
 	}
 	
 	/**
 	 * @desc 根据采购入库id 获取明细信息（导入采购入库）
 	 * @author liaojianwen
 	 * @date 2017-04-27
 	 */
 	public function getPurDetail($id)
 	{
 		if (empty ( $id )) {
 			return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'param is empty' );
 		}
 		$fields = [
 				'purchase_det_id',
 				'd.purchase_id',
 				'd.goods_id',
 				'p.product_name',
 				'p.product_sn',
 				'd.quantity',
 				'd.quantity_unit',
 				'u.unit_name',
 				'd.price',
 				'd.amount',
 				'd.remark',
 				'd.minus_quantity',
 				'd.return_quantity',
 		];
 	
 		$joinArr = [
 				[
 						"product p",
 						"p.product_id = d.goods_id",
 				],
 				[
 						"unit u",
 						"u.unit_id = d.quantity_unit",
 				]
 		];
 		$conditions = "d.purchase_id = :id and d.delete_flag = :dflag and d.finish_flag =:fflag";
 		$params = [
 				':id' => $id,
 				':dflag' => EnumOther::NO_DELETE,
 				':fflag' => EnumOther::NO_FINISHED,
 		];
 		$result = PurchaseDetailDAO::getInstance()->iselect($fields, $conditions, $params, 'all',"purchase_det_id ASC", $joinArr,'d');
 		if(empty($result)){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','detail no data found');
 		}
 		return $this->handleApiFormat ( EnumOther::ACK_SUCCESS, $result );
 	}
 	
 	
 	/**
 	 * @desc 检查出库单是否被退货单占用
 	 * @author liaojianwen
 	 * @date 2017-04-25
 	 */
 	public function checkPurchaseById($id)
 	{
 		if(!$id){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','param is empty');
 		}
 		$result = PurchaseReturnDAO::getInstance ()->findByAttributes ( "purchase_return_id", "purchase_id =:pid and confirm_flag=:flag and delete_flag =:dflag", [
 				':pid' => $id,
 				':flag' => EnumOther::NO_CONFIRM ,
 				':dflag' => EnumOther::NO_DELETE,
 		] );
 		if(empty($result)){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','');
 		}
 		return $this->handleApiFormat(EnumOther::ACK_SUCCESS,'');
 	}
 	
 	
 	/**
 	 * @desc 保存采购退货单据
 	 * @param [] $head 单头内容
 	 * @param [] $detail 明细内容
 	 * @param int $id 采购退货单内容
 	 * @author liaojianwen
 	 * @date 2017-04-28
 	 */
 	public function savePurchaseReturn($head, $detail, $remove, $id)
 	{
 		if(empty($head)){
 			return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'head is empty' );
 		}
 		if (empty ( $detail )) {
 			return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'detail is empty' );
 		}
 		if(empty($id)){
 			$id = 0;
 		}
 			
 		foreach ($head as $k =>$hed){
 			if(empty($hed)){
 				unset($head[$k]);
 			}
 		}
 		foreach ($detail as $k=> $det){
 			foreach ($det as $j => $deet){
 				if(empty($deet)){
 					unset($detail[$k][$j]);
 				}
 			}
 		}
 		// 表头信息
 		$head ['purchase_return_date'] = strtotime ( $head ['purchase_return_date'] );
 		$cond_head = "purchase_return_id =:id";
 		$param_head = [
 				':id' => $id
 		];
 		$Iid = PurchaseReturnDAO::getInstance ()->ireplaceinto ( $head, $cond_head, $param_head, true );
 		if (! $Iid) {
 			$tr->rollBack();
 			return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'save purchase_return_head failure' );
 		}
 		// 表单明细
 		foreach ($remove as $move){
 			$res_remove = PurchaseReturnDetailDAO::getInstance()->iupdate(['delete_flag'=>EnumOther::DELETED], "purchase_return_det_id = :det_id", [':det_id'=>$move['purchase_return_det_id']]);
 			if(!$res_remove){
 				$tr->rollBack();
 				$this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'remove purchase_return_det_id:'+$move['purchase_return_det_id'] +'failed');
 			}
 		}
 		foreach ( $detail as &$det ) {
 			$det ['purchase_return_id'] = $Iid;
 			$det ['delete_flag'] = EnumOther::NO_DELETE;
 			$cond_det = "purchase_return_id = :id and purchase_return_det_id = :lid";
 			$param_det = [
 					':id' => $Iid,
 					':lid' =>  isset($det ['purchase_return_det_id'])?$det['purchase_return_det_id']:0
 			];
 			//确认的时候写
 			$res_det = PurchaseReturnDetailDAO::getInstance ()->ireplaceinto ( $det, $cond_det, $param_det, true );
 			if (! $res_det) {
 				return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'save purchase_return_detail failure' );
 			}
 		}
 			
 		return $this->handleApiFormat ( EnumOther::ACK_SUCCESS, '' );
 	}
 	
 	/**
 	 * @desc 获取采购退货单列表
 	 * @param [] $pageInfo 页面信息
 	 * @param [] $condition 查询信息
 	 * @author liaojianwen
 	 * @date 2017-04-28
 	 */
 	public function getPurchaseReturn($pageInfo, $condition)
 	{
 		if(empty($pageInfo)){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','pageInfo is empty');
 		}
 		$result = PurchaseReturnDAO::getInstance()->getPurchaseReturn($condition, $pageInfo);
 		if(empty($result)){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','no data found');
 		}
 		return $this->handleApiFormat(EnumOther::ACK_SUCCESS,$result);
 	}
 	
 	/**
 	 * @desc 根据采购退货单id 获取退货单信息
 	 * @param int $id
 	 * @author liaojianwen
 	 * @date 2017-04-28
 	 */
 	public function getPurchaseReturnInfo($id)
 	{
 		if(empty($id)){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','param is empty');
 		}
 		$pur_head = PurchaseReturnDAO::getInstance()->getPurchaseReturnHead($id);
 		if(empty($pur_head)){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','head data found');
 		}
 		$pur_det = PurchaseReturnDetailDAO::getInstance()->getPurchaseReturnDet($id);
 		if(empty($pur_det)){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','detail data found');
 		}
 		$result['head'] = $pur_head;
 		$result['det'] = $pur_det;
 		return $this->handleApiFormat(EnumOther::ACK_SUCCESS,$result);
 	}
 	
 	/**
 	 * @desc 获取采购入库明细
 	 * @author liaojianwen
 	 * @date 2017-04-28
 	 */
 	public function getPurchaseReturnDet($id)
 	{
 		if (! $id) {
 			return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'param is empty' );
 		}
 		$fields = [
 				'purchase_return_det_id',
 				'd.purchase_return_id',
 				'd.product_id',
 				'p.product_name',
 				'p.product_sn',
 				'd.quantity',
 				'd.quantity_unit',
 				'u.unit_name',
 				'd.price',
 				'd.amount',
 				'd.remark',
//  				'd.minus_quantity',
//  				'd.return_quantity'
 		];
 	
 		$joinArr = [
 				[
 						"product p",
 						"p.product_id = d.product_id"
 				],
 				[
 						"unit u",
 						"u.unit_id = d.quantity_unit"
 				]
 		];
 		$conditions = "d.purchase_return_id = :id and d.delete_flag = :dflag";
 		$params = [
 				':id' => $id,
 				':dflag' => EnumOther::NO_DELETE,
 		];
 		$result = PurchaseReturnDetailDAO::getInstance()->iselect($fields, $conditions, $params, 'all',"purchase_det_id ASC", $joinArr,'d');
 		if(empty($result)){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','no data found');
 		}
 		return $this->handleApiFormat(EnumOther::ACK_SUCCESS, $result);
 	}
 	
 	
 	/**
 	 * @desc 确认采购退货单(相当于出库)
 	 * @author liaojianwen
 	 * @date 2017-04-28
 	 */
 	public function confirmPurchaseReturn($id)
 	{
 		if (! $id) {
 			return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'param is empty' );
 		}
 		$id = (int)$id;
 		$tr = Yii::$app->db->beginTransaction ();
 		try {
 			$re_confirm = PurchaseReturnDAO::getInstance ()->updateByPk ( $id, [
 					'confirm_flag' => EnumOther::CONFIRM
 			] );
 			if (! $re_confirm) {
 				$tr->rollBack ();
 				return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'confirm fail' );
 			}
 	
 			//采购订单id
 			$select_arr = [
 					'purchase_return_id',
 					'purchase_return_no',
 					'purchase_id',
 					'vendor_id',
 					'purchase_return_date',
 					'purchase_return_amount',
 					'purchase_return_type',
 					'purchase_return_man',
 					'remark',
 			];
 			$pro_res = PurchaseReturnDAO::getInstance()->iselect($select_arr, "purchase_return_id =:pid", [':pid'=>$id],'one');//['procurement_id']
 			$purchase_id = $pro_res['purchase_id'];
 			$fields = [
 					'h.purchase_return_no',
 					'd.product_id',
 					'd.quantity',
 					'h.purchase_return_type',
 					'd.purchase_return_det_id',
 					'h.warehouse_id',
 					'd.purchase_det_id',
 					'h.purchase_return_date',
 					'h.vendor_id',
 					'd.quantity_unit',
 					'd.base_quantity',
 					'd.base_unit',
 					'd.base_price',
 					's.quantity squantity'
 			];
 			$conditions = "d.purchase_return_id =:id and d.delete_flag = :flag";
 			$params = [
 					':id' => $id,
 					':flag' => EnumOther::NO_DELETE
 			];
 			$joinArray = [
 					[
 							'purchase_return h',
 							"h.purchase_return_id = d.purchase_return_id"
 					],
 					[
 							'stock_pile s',
 							's.product_id  = d.product_id and s.warehouse_id = h.warehouse_id'
 					]
 			];
 			$purchase_return_det = PurchaseReturnDetailDAO::getInstance ()->iselect ( $fields, $conditions, $params, 'all', 'd.purchase_return_det_id ASC', $joinArray, 'd' );
 			if (! $purchase_return_det) {
 				$tr->rollBack ();
 				return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'select det fail' );
 			}
 			// 出入库明细
 			$finish_flag = 0;//采购订单整单是否完成的标记
 			foreach ( $purchase_return_det as $det ) {
 				$PRODUCT = ProductDAO::getInstance()->iselect(["price","quantity","product_name"], "product_id = :pid", [':pid'=>$det['product_id']],'one');
 				if(isset($PRODUCT['price'])){
 					$price = $PRODUCT['price'];
 				} else {
 					$price = 0;
 				}
 				if($det['base_quantity'] > $det['squantity']){
 					$tr->rollBack();
 					return $this->handleApiFormat(EnumOther::ACK_FAILURE, $PRODUCT['product_name'], 'overflow quantity');
 				}
 				$column_trans = array (
 						'goods_id' => $det ['product_id'],
 						'quantity' => $det ['base_quantity'],
 						'quantity_unit' => $det['base_unit'],
 						'origin_type' => $det ['purchase_return_type'],
 						'origin_id' => $det ['purchase_return_no'],
 						'origin_line_id' => $det ['purchase_return_det_id'], // 原单序号
 						'origin_time'=> $det['purchase_return_date'],
 						'vendor_id'=> $det['vendor_id'],
 						'warehouse_id' => $det ['warehouse_id'],
 						'init_num' => $PRODUCT['quantity'],//上期数量
 						'flag' => EnumOther::OUT_FLAG
 				);
 					
 				$res_trans = TransactionDAO::getInstance ()->iinsert ( $column_trans, true );
 				if (! $res_trans) {
 					$tr->rollBack ();
 					return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'save transaction failure' );
 				}
 				
 				//商品成本价计算 --start
 				$priceRes = PurchaseModel::model()->AccountingPrice($det['product_id'], $det['base_quantity'], $det['base_price'], false, EnumOriginType::origin_purchase_return);
 				if(!$priceRes){
 					$tr->rollBack();
 					return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'accounting price fail');
 				}
 				////----end
 	
 				// 	更新product quantity 减库存
 				$pro_select = ProductDAO::getInstance ()->updateAllCounters ( [
 						'quantity' => -$det ['base_quantity'],
 						'amount'=> -($price * $det['base_quantity']),
 				], "product_id =:id", [
 						':id' => $det ['product_id']
 				] );
 					
 				if (! $pro_select) {
 					$tr->rollBack ();
 					return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'update product quantity failure' );
 				}
 					
 				//product_update_log 商品更新记录//
 				$_order_type = Utility::getArrayValue(EnumOriginType::$origin_type, $det['purchase_return_type']);
 					
 				$log_columns = [
 						'product_id' => $det ['product_id'],
 						'update_num' => $det ['base_quantity'],
 						'num_unit' => $det['base_unit'],
 						'origin_id' => $id,
 						'origin_no' => $det['purchase_return_no'],
 						'origin_line_id'=> $det['purchase_return_det_id'],
 						'origin_type'=> $det['purchase_return_type'],
 						'update_time'=>strtotime(date('Y-m-d')),
 						'flag'=> EnumOther::OUT_FLAG,
 						'initial_num'=> $PRODUCT['quantity'],//上期数量
 						'remark'=> $_order_type . EnumOther::MINUS,
 						'warehouse_id' => $det['warehouse_id'],
 						'create_man' => Yii::$app->user->id,
 				];
 				$res_log = ProductUpdateLogDAO::getInstance()->iinsert($log_columns, true);
 				if(! $res_log){
 					$tr->rollBack();
 					return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'product update log failure');
 				}
 					
 				//采购订单表回写//是由导入采购订单的入库单才要执行下面代码
 				if($purchase_id){
 					$pro_finish = PurchaseDetailDAO::getInstance()->updateFinish($purchase_id,$det);
 					if($pro_finish['Ack'] == 'error'){
 						$tr->rollBack();
 						return $this->handleApiFormat(EnumOther::ACK_FAILURE,'',$pro_finish['msg']);
 					}
 				}
 					
 					
 				//分仓列表数据的插入或者更新--start
 				$stock_conditions = "warehouse_id =:wid and product_id=:pid and delete_flag =:flag";
 				$stock_params = [
 						':wid'=>$det['warehouse_id'],
 						':pid' => $det ['product_id'],
 						':flag' => EnumOther::NO_DELETE
 				];
 				$stock_select = StockPileDAO::getInstance ()->iselect ( "stock_pile_id", $stock_conditions, $stock_params, 'one' );
 				if (! $stock_select) {
 					// 没有数据，插入新数据 //入库
 						
//  					$stock_columns = [
//  							'warehouse_id' => $det ['warehouse_id'],
//  							'product_id' => $det ['goods_id'],
//  							'quantity' => $det ['base_quantity'],
//  							'quantity_unit' => $det ['base_unit']
//  					];
//  					$stock_insert = StockPileDAO::getInstance ()->iinsert ( $stock_columns, true );
//  					if (! $stock_insert) {
 						$tr->rollBack ();
 						return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'insert stock pile failure' );
//  					}
 				} else {
 					//有数据，更新数据
 					$stock_update = StockPileDAO::getInstance()->updateAllCounters(['quantity'=> - $det['base_quantity']], $stock_conditions, $stock_params);
 					if(! $stock_update){
 						$tr->rollBack();
 						return $this->handleApiFormat(EnumOther::ACK_FAILURE, '','update stock pile failure');
 					}
 				}
 				//分仓 --end
 					
 				//应付单数据表数据插入 --start/////应付账单
 				$column_pay = [
 						'origin_id' => $pro_res['purchase_return_id'],
 						'origin_no' => $pro_res['purchase_return_no'],
 						'origin_type' => $pro_res['purchase_return_type'],
 						'pay_time' => $pro_res['purchase_return_date'],
 						'pay_type'=> EnumOriginType::origin_purchase_return,
 						'vendor_id' => $pro_res['vendor_id'],
 						'pay_man' => $pro_res['purchase_return_man'],
 						'pay_amount' => -$pro_res['purchase_return_amount'],
 						'settle_amount' => -$pro_res['purchase_return_amount'],
 						'left_amount' => -$pro_res['purchase_return_amount'],
 						'description' => '应付账单，采购退货单',
 						'remark'=> $pro_res['remark'],
 						'create_man' => Yii::$app->user->id,
 	
 				];
 				$cond = "origin_id = :oid and delete_flag = :flag";
 				$param =[
 						':oid'=> $pro_res['purchase_return_id'],
 						':flag'=> EnumOther::NO_DELETE,
 				];
 				$res_pay = PayablesDAO::getInstance()->ireplaceinto($column_pay, $cond, $param,true);
 				if(! $res_pay){
 					$tr->rollBack();
 					return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'insert payables fail');
 				}
 				//应付单 --end
 					
 			}
 	
 			$tr->commit();
 			return $this->handleApiFormat(EnumOther::ACK_SUCCESS,'');
 		} catch ( \Exception $e ) {
 			$tr->rollBack ();
 			return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', $e->getMessage());
 		}
 	}
 	
 	/**
 	 * @desc 导入采购入库单信息
 	 * @author liaojianwen
 	 * @date 2017-05-03
 	 */
 	public function implodePurchaseInfo($id)
 	{
 		if(empty($id)){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','param is empty');
 		}
 		$pur_head = PurchaseDAO::getInstance()->getPurchaseHead($id);
 		if(empty($pur_head)){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','head data found');
 		}
 		$pur_det = PurchaseDetailDAO::getInstance()->getPurchaseDet($id);
 		if(empty($pur_det)){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','detail data found');
 		}
 		foreach ($pur_det as &$det)
 		{
 			$det['left_quantity'] = $det['minus_quantity'];
 			foreach ( $det['product_unit'] as $unit){
 				if($det['quantity_unit'] == $unit['unit_id']){
 					$det['quantity_rate'] = $unit['rate'];
 					$det['quantity_name'] = $unit['unit_name'];
 				}
 				if($det['second_unit'] == $unit['unit_id']){
 					$det['second_rate'] = $unit['rate'];
 					$det['second_name'] = $unit['unit_name'];
 				}
 			}
 		
 			if($det['second_unit'] ){
 				$det['second_quantity'] = $det['minus_quantity'] / $det['second_rate'];
 			}
 		
 			$det['quantity'] = $det['minus_quantity'] / $det['quantity_rate'];
 			$det['amount'] = round($det['quantity'] * $det['price'],2);
 		
 			if($det['second_unit'] ){
 				$tmp_name = floor($det ['quantity'] * $det ['quantity_rate'] / $det ['second_rate']);
 				$tmp_content = fmod($det ['quantity']*$det['quantity_rate'],$det['second_rate']);
 				$det['second_relation'] = $tmp_name. $det['second_name'] .$tmp_content . $det['quantity_name'];
 			}
 		
 		}
//  		dd($pur_det);
 		$result['head'] = $pur_head;
 		$result['det'] = $pur_det;
 		return $this->handleApiFormat(EnumOther::ACK_SUCCESS,$result);
 	}
 	
 /**
 	 * @desc 删除采购退货（相当于入库）
 	 * @author liaojianwen
 	 * @date 2016-12-14
 	 */
 	public function delPurchaseReturn($ids)
 	{
 		if(empty($ids)){
 			return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'param is empty' );
 		}
 		$_ids = explode ( ',', $ids );
 		
 		$tT = Yii::$app->db->beginTransaction ();
 		try {
 			foreach ( $_ids as $id ) {
 				$res_purchase = PurchaseReturnDAO::getInstance ()->updateByPk ( $id, ['delete_flag' => EnumOther::DELETED] );
 				if(!$res_purchase){
 					$tT->rollBack();
 					return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'del_purchase_return fail');
 				}
 				//purchase_return_detail
 				$purchase_det = PurchaseReturnDetailDAO::getInstance()->iupdate(['delete_flag'=>EnumOther::DELETED], "purchase_return_id=:id", [':id'=>$id]);
 				if(!$purchase_det){
 					$tT->rollBack();
 					return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','del_purchase_det fail');
 				}
//  				//删除生成的采购应付
//  				$res_payable = PayablesDAO::getInstance()->iupdate(['delete_flag'=>EnumOther::DELETED], "origin_id =:oid", [':oid'=>$id]);
//  				if(!$res_payable){
//  					$tT->rollBack();
//  					return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'delete payable failed');
//  				}
//  				$procurement_id = 0;
 				//更新product_quantity
 				$fields = [
 						't.goods_id',
 						't.quantity',
 						't.transaction_id',
 						'i.warehouse_id',
 						'i.purchase_return_no',
 						'd.quantity_unit',
 						'i.purchase_return_type',
 						'd.purchase_return_det_id',
 						'i.purchase_id',
 						'd.purchase_det_id'
 				];
 				$conditions = "t.delete_flag = :flag";
 				$params = [
 						':flag'=>EnumOther::NO_DELETE,
 				];
 				$joinArray = [
 						[
 								'purchase_return i',
 								'i.purchase_return_no = t.origin_id and i.purchase_return_id = '.$id,
 								'right'=>'',
 						],
 						[
 								'purchase_return_detail d',
 								'd.purchase_return_det_id = t.origin_line_id',
 								'left'=>''
 						]
 						
 				];
 				$trans_select = TransactionDAO::getInstance()->iselect($fields, $conditions, $params,'all',"t.create_time ASC",$joinArray,'t');
 				if (! empty ( $trans_select )) {
 					// 已确认的入库单才有transtions,减库存
 					foreach ( $trans_select as $trans ) {
 						
//  						$procurement_id = $trans['procurement_id'];
 						//记录更新product 前的quantity
 						$PRODUCT = ProductDAO::getInstance()->iselect("quantity", "product_id = :pid", [':pid'=>$trans['goods_id']],'one');
 						//更新product quantity
 						$return_plus = ProductDAO::getInstance ()->updateAllCounters ( [
 								'quantity' => $trans ['quantity'],
 						], "product_id =:id", [
 								':id' => $trans ['goods_id']
 						] );
 							
 						if (! $return_plus) {
 							$tT->rollBack();
 							return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'update product quantity failure' );
 						}
 		

 						//product_update_log 商品更新记录
 						$_order_type = Utility::getArrayValue(EnumOriginType::$origin_type, $trans['purchase_return_type']);
 						
 						$log_columns = [
 								'product_id' => $trans ['goods_id'],
 								'update_num' => $trans ['quantity'],
 								'num_unit' => $trans['quantity_unit'],
 								'origin_id' => $id,
 								'origin_no' => $trans['purchase_return_no'],
 								'origin_line_id'=> $trans['purchase_return_det_id'],
 								'origin_type'=> $trans['purchase_return_type'],
 								'update_time'=>strtotime(date('Y-m-d')),
 								'flag'=> EnumOther::IN_FLAG,
 								'initial_num'=> $PRODUCT['quantity'],//上期数量
 								'remark'=> $_order_type . EnumOther::PLUS.',采购退货单删除',
 								'warehouse_id' => $trans['warehouse_id'],
 								'create_man' => Yii::$app->user->id,
 						];
 						$res_log = ProductUpdateLogDAO::getInstance()->iinsert($log_columns, true);
 						if(! $res_log){
 							$tT->rollBack();
 							return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'product update log failure');
 						}
 						
 						//删除transaction 数据
 						$columns = [
 								'delete_flag'=>EnumOther::DELETED,
 						];
 						$conditions = "transaction_id = :tid";
 						$params = [
 								':tid'=>$trans['transaction_id'],
 						];
 						$trans_update = TransactionDAO::getInstance()->iupdate($columns, $conditions, $params);
 		
 						if(empty($trans_update)){
 							$tT->rollBack();
 							return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','tansaction del fail');
 						}
 						
 						// 更新stock_file 分仓表信息
 						$stock_plus = StockPileDAO::getInstance ()->updateAllCounters ( [
 								'quantity' => $trans ['quantity']
 						], "warehouse_id =:wid and product_id=:pid and delete_flag =:flag", [
 								':wid' => $trans ['warehouse_id'],
 								':pid' => $trans ['goods_id'],
 								':flag' => EnumOther::NO_DELETE
 						] );
 						if(! $stock_plus){
 							$tT->rollBack ();
 							return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'update stock pile quantity failure');
 						}
 						
 						//更新procurement
 						if($trans['purchase_id']){
	 						$result = PurchaseDAO::getInstance()->updatePurchase($trans['purchase_id'],$trans['purchase_det_id'],$trans['quantity']);
	 						if(!$result){
	 							$tT->rollBack();
	 							return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'update procurement failure');
	 						}
	 					}
 		
 					}
 				
 					
 				}

 			}
 			$tT->commit();
 			return $this->handleApiFormat(EnumOther::ACK_SUCCESS,'');
 		} catch ( \Exception $e ) {
 			$tT->rollBack ();
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'',$e->getMessage());
 		}
 	}
 	
 }